﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Windows.Threading;
using System.Runtime.Serialization.Formatters.Binary;

namespace Auktionshuset
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private const int PORT = 12345;

        private NetworkStream networkstream;
        private StreamReader streamreader;
        private StreamWriter streamwriter;
        private Socket server;
        private IPEndPoint serveradr;
        Thread klientStart;
        private BroadcastKlientTraad broadcastKlientTraad;
        private Produkt produkt;
        private int time = 31;
        DispatcherTimer t = new DispatcherTimer();

        public delegate void ModtagBroadcast(string sidsteBud);

        public MainWindow()
        {
            InitializeComponent();

            this.serveradr = new IPEndPoint(IPAddress.Loopback, PORT);

            produkt = new Produkt();

            broadcastKlientTraad = new BroadcastKlientTraad();

            broadcastKlientTraad.ModtagBroadcastEvent += new Auktionshuset.ModtagBroadcast(ChatModtagetHandler);

            t.Interval = new TimeSpan(0, 0, 1);
            t.Tick += new EventHandler(t_Tick);
        }

        public void ChatModtagetHandler(string sidsteBud)
        {
            txtStartPris.Dispatcher.BeginInvoke(new ModtagBroadcast(chatModtagetHandlerInvoke), sidsteBud);
        }

        private void chatModtagetHandlerInvoke(string sidsteBud)
        {
            txtStartPris.Text = sidsteBud;
        }

        private void btnlogpå_Click(object sender, RoutedEventArgs e)
        {
            this.server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            
            try
            {
                this.server.Connect(this.serveradr);
            }
            catch (SocketException ex)
            {
                Console.WriteLine("Kan ikke forbinde til server...");
                Console.WriteLine(ex.ToString());
                return;
            }

            this.networkstream = new NetworkStream(this.server);
            this.streamreader = new StreamReader(this.networkstream);
            this.streamwriter = new StreamWriter(this.networkstream);

            txtProduktNavn.Text = produkt.Navn;
            txtBeskrivelse.Text = produkt.Beskrivelse;
            txtVarensStand.Text = produkt.Varestand;
            txtVarenummer.Text = produkt.VareNr.ToString();
            txtStartPris.Text = produkt.SidsteBud.ToString();

            BitmapImage bmi = new BitmapImage(new Uri(".../Images/BMW-bmw-34154811-1600-1066.jpg", UriKind.Relative));
            imgProdukt.Source = bmi;

            klientStart = new Thread(new ParameterizedThreadStart(broadcastKlientTraad.ModtagChatInput));
            klientStart.Start(streamreader);

            btnlogpå.IsEnabled = false;
        }

        void t_Tick(object sender, EventArgs e)
        {
            if (time > 0)
            {
                if (time <= 100)
                {
                    time--;
                    lbTid.Content = string.Format("00:0{0}:{1}", time / 60, time % 60);
                }
            }
            else
            {
                t.Stop();
                MessageBox.Show("Tiden er stoppet!");
                time = 11;
                t.Start();
                MessageBox.Show("Vinderens IPAdresse: " + serveradr.ToString());
            }
            
        }

        private void btnlogaf_Click(object sender, RoutedEventArgs e)
        {
            this.streamreader.Close();
            this.streamwriter.Close();
            this.networkstream.Close();
            this.server.Shutdown(SocketShutdown.Both);
            this.server.Close();

            btnlogaf.IsEnabled = false;
            btnlogpå.IsEnabled = true;
        }

        private void btnByd_Click(object sender, RoutedEventArgs e)
        {
            t.Start();

            decimal sidsteBud;
            decimal beløb = decimal.Parse(txtDitBud.Text);
            if (beløb > produkt.SidsteBud)
            {
                sidsteBud = produkt.Byd(beløb);
                txtStartPris.Text = sidsteBud.ToString();
                streamwriter.WriteLine(txtDitBud.Text);
                streamwriter.Flush();
                txtStartPris.IsEnabled = false;
            }
            else
            {
                MessageBox.Show("Dit bud er ikke højt nok.");
            }

            txtDitBud.Clear();
            txtDitBud.Focus();
        }
        private void imgProdukt_MouseEnter(object sender, MouseEventArgs e)
        {
            Image img = ((Image)sender);
            img.Height = img.ActualHeight * 2.0;
            img.Width = img.ActualHeight * 2.0;
        }

        private void imgProdukt_MouseLeave(object sender, MouseEventArgs e)
        {
            Image img = ((Image)sender);
            img.Height = 240;
            img.Width = 314;
        }

    }
}
